package com.ushine.web.communication.websocket.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: yls
 * @Date 2022/5/7 17:11
 * @Description: ws地址方式：原生支持方式
 * @Version 1.0
 **/
@ServerEndpoint("/android/{userId}")
@Component
@Slf4j
public class WebsocketServer {

    private static final String MODEL = "webSocket通信=ws方式=》";

    public WebsocketServer() {
        //每当有一个连接，都会执行一次构造方法
        log.info("{}新的连接。。。", MODEL);
    }

    /**
     * 存放当前连接数
     */
    private static final AtomicInteger COUNT = new AtomicInteger();


    /**
     * 存放所有的连接
     */
    private static final ConcurrentHashMap<String, Session> SESSIONS = new ConcurrentHashMap<>();


    /**
     * 功能描述:
     * 〈发送消息〉
     *
     * @param toSession 发送的session
     * @param message   发送信息
     * @return : void
     * @throws
     * @author : yls
     * @date : 2022/5/7 17:24
     */
    public void sendMessage(Session toSession, String message) {
        if (toSession != null) {
            try {
                toSession.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            log.info("{}对方不在线", MODEL);
        }
    }

    public void sendMessageToUser(String user, String message) {
        Session toSession = SESSIONS.get(user);
        sendMessage(toSession, message);
    }


    @OnMessage
    public void onMessage(String message) {
        log.info("{}服务器收到消息：{}", MODEL, message);
        String userId = "123456";
        sendMessageToUser(userId, MODEL + "你好，欢迎连接");
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        if (SESSIONS.get(userId) != null) {
            return;
        }
        SESSIONS.put(userId, session);
        COUNT.incrementAndGet();
        log.info("{}{}上线了，当前在线人数：{}", MODEL, userId, COUNT);
    }

    @OnClose
    public void onClose(@PathParam("userId") String userId) {
        SESSIONS.remove(userId);
        COUNT.decrementAndGet();
        log.info("{}{}上线了，当前在线人数：{}", MODEL, userId, COUNT);
    }


    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("{}{}出错了，当前在线人数：{}", MODEL, session, COUNT, throwable);
    }
}
